<?php

namespace app\api\controller;

use AlibabaCloud\Client\AlibabaCloud;
use AlibabaCloud\Client\Exception\ClientException;
use AlibabaCloud\Client\Exception\ServerException;

class AliCloudController extends BaseApiController
{

    //调用STS服务AssumeRole
    public function getAuth()
    {

        //构建一个阿里云客户端，用于发起请求。
        //设置调用者（RAM用户或RAM角色）的AccessKey ID和AccessKey Secret。
        $aliyun = [
            "AccessKeyId" => "LTAI5tK3vJrP8aDCtCeQGo8n",
            "AccessKeySecret" => "7DiFSH9z1Z14Wr81H4gui6iOPC85wF",
            "RegionId" => "oss-cn-hangzhou",
            "RoleArn" => "acs:ram::1420181514912677:role/oss-ram",
            "RoleSessionName" => "lite-meoyun-com",
        ];

        AlibabaCloud::accessKeyClient($aliyun["AccessKeyId"], $aliyun["AccessKeySecret"])
            ->regionId('cn-hangzhou')
            ->asDefaultClient();
        try {
            $result = AlibabaCloud::rpc()
                ->product('Sts')
                ->scheme('https') // https | http
                ->version('2015-04-01')
                ->action('AssumeRole')
                ->method('POST')
                ->host('sts.aliyuncs.com')
                ->options([
                    'query' => [
                        'RegionId' => $aliyun["RegionId"],
                        'RoleArn' => $aliyun["RoleArn"],
                        'RoleSessionName' => $aliyun["RoleSessionName"]
                    ],
                ])
                ->request();

            return $this->data(array_merge($result->toArray(), $aliyun));
        } catch (ClientException $e) {
            return $this->fail($e->getErrorMessage());
        } catch (ServerException $e) {
            return $this->fail($e->getErrorMessage());
        }
    }
}